package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.domain.YdAccountHead;
import com.zhentao.domain.dto.AllDto;
import com.zhentao.domain.dto.StatusDto;
import com.zhentao.domain.dto.IncomeAndPayItemDto;
import com.zhentao.domain.vo.IncomeAndPayItemVo;
import com.zhentao.service.YdAccountHeadService;
import com.zhentao.mapper.YdAccountHeadMapper;
import com.zhentao.util.Result;
import com.zhentao.util.ThreadLoadUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
* @author 小明
* @description 针对表【yd_account_head(财务主表)】的数据库操作Service实现
* @createDate 2024-10-23 09:53:31
*/
@Service
public class YdAccountHeadServiceImpl extends ServiceImpl<YdAccountHeadMapper, YdAccountHead>
    implements YdAccountHeadService{

    @Autowired
    private YdAccountHeadMapper ydAccountHeadMapper;

    @Override
    public Result accountList(AllDto allDto) {
        PageHelper.startPage(allDto.getPage(), allDto.getSize());
        List<YdAccountHead> ydAccountHeads = ydAccountHeadMapper.accountList(allDto);
        PageInfo<YdAccountHead> ydAccountHeadPageInfo = new PageInfo<>(ydAccountHeads);
        return Result.success().put("data", ydAccountHeadPageInfo.getList()).put("total",ydAccountHeadPageInfo.getTotal()).put("page", ydAccountHeadPageInfo.getPageNum()).put("size", ydAccountHeadPageInfo.getPageSize());
    }

    @Override
    public Result AccountHeadSave(YdAccountHead ydAccountHead) {
        //1、判断改数据是否存在
        YdAccountHead selectedById = ydAccountHeadMapper.selectById(ydAccountHead.getId());
        if (selectedById != null){
            ydAccountHead.setCreator(ThreadLoadUser.getId());
            int i = ydAccountHeadMapper.updateById(ydAccountHead);
            if (i == 1){
                return Result.success("操作成功");
            }
        }else {
            ydAccountHead.setCreator(ThreadLoadUser.getId());
            ydAccountHead.setBillTime(new Date());
            ydAccountHead.setStatus(0);
            ydAccountHead.setDeleteFlag(0);
            int insert = ydAccountHeadMapper.insert(ydAccountHead);
            if (insert == 1){
                return Result.success("操作成功");
            }
        }
        return Result.error("操作失败");
    }

    @Override
    public Result accountSelectOne(Integer id) {
        //1、判断这条单据是否存在
        if (id == null){
            return Result.error("单据id不能为空");
        }
        YdAccountHead ydAccountHead = ydAccountHeadMapper.accountSelectOne(id);
        return Result.success().put("data", ydAccountHead);
    }

    @Override
    public Result AccountHeadDel(Integer id) {
        //1、判断这条单据是否存在
        if (id == null){
            return Result.error("单据id不能为空");
        }
        int i = ydAccountHeadMapper.deleteById(id);
        if (i == 1){
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }
    @Transactional
    @Override
    public Result AccountHeadDels(Integer[] ids) {
        // 判断传入的数组是否为空
        if (ids == null || ids.length == 0) {
            return Result.error("单据id数组不能为空");
        }

        boolean operationSuccessful = true;
        for (Integer id : ids) {
            // 判断这条数据是否存在
            if (id == null) {
                return Result.error("单据id不能为空");
            }
            YdAccountHead ydAccountHead = ydAccountHeadMapper.selectById(id);
            if (ydAccountHead == null) {
                return Result.error("单据不存在");
            }
            int result = ydAccountHeadMapper.deleteById(id);
            if (result != 1) { // 假设删除失败返回的不是1
                operationSuccessful = false;
                break; // 退出循环，不再尝试删除其他ID
            }
        }

        if (operationSuccessful) {
            return Result.success("操作成功");
        } else {
            return Result.error("操作失败");
        }
        }

    @Override
    public Result AccountHeadStatus(StatusDto statusDto) {

        // 判断传入的数组是否为空
        if (statusDto.getIds() == null || statusDto.getIds().length == 0) {
            return Result.error("单据id数组不能为空");
        }

        // 遍历数组，对每个id进行处理
        for (Integer id : statusDto.getIds()) {
            // 判断这条数据是否存在
            if (id == null) {
                return Result.error("单据id不能为空");
            }
            YdAccountHead ydAccountHead = ydAccountHeadMapper.selectById(id);
            if (ydAccountHead == null) {
                return Result.error("单据不存在");
            }

            // 根据 isReverse 参数决定操作
            if (statusDto.getIsReverse()) {
                // 执行反审核操作
                if (ydAccountHead.getStatus() == 1 || ydAccountHead.getStatus() == 0) {
                    ydAccountHead.setStatus(2); // 将状态设置为审核失败
                    int i = ydAccountHeadMapper.updateById(ydAccountHead);
                    if (i != 1) {
                        // 如果更新失败，返回错误信息
                        return Result.error("单据id为 " + id + " 的反审核操作失败");
                    }
                }
            } else {
                // 执行审核操作
                ydAccountHead.setStatus(1); // 将状态设置为审核成功
                int i = ydAccountHeadMapper.updateById(ydAccountHead);
                if (i != 1) {
                    // 如果更新失败，返回错误信息
                    return Result.error("单据id为 " + id + " 的审核操作失败");
                }
            }
        }

        // 如果所有id都处理成功
        return Result.success("操作成功");
    }



    //    收支项明细
    @Override
    public PageInfo<IncomeAndPayItemVo> IncomeOrPayList(IncomeAndPayItemDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<IncomeAndPayItemVo> incomeAndPayItemVos = ydAccountHeadMapper.IncomeOrPayList(dto);
        PageInfo<IncomeAndPayItemVo> incomeAndPayItemVoPageInfo = new PageInfo<>(incomeAndPayItemVos);
        return incomeAndPayItemVoPageInfo;
    }

    //    导出
    @Override
    public void exportData(HttpServletResponse response,IncomeAndPayItemDto dto) {
        try {

            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据打印", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 查询数据库中的数据
            PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
            List<IncomeAndPayItemVo> incAndPayList = ydAccountHeadMapper.ExcelIncAndPayList();
            PageInfo<IncomeAndPayItemVo> pageInfo = new PageInfo<>(incAndPayList);


            // 写出数据到浏览器端
//            EasyExcel.write(response.getOutputStream(), IncomeAndPayItemVo.class).sheet("分类数据").doWrite(pageInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    收付款明细
    @Override
    public PageInfo<IncomeAndPayItemVo>  rcvOrMakeList(IncomeAndPayItemDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<IncomeAndPayItemVo> incomeAndPayItemVos = ydAccountHeadMapper.rcvOrMakeList(dto);
        PageInfo<IncomeAndPayItemVo> pageInfo = new PageInfo<>(incomeAndPayItemVos);
        return pageInfo;
    }
}




